<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { storage } from '../../stores/mystore/auth'
import { Notify, showConfirmDialog, showNotify, Toast } from 'vant'

const router = useRouter()

// 定义TAB配置
const tabs = [
  // { key: 'all', title: '全部' },
  { key: 'pending', title: '待处理' },
  { key: 'processing', title: '处理中' },
  { key: 'done', title: '已处理' },
]

// 响应式状态定义
const activeTab = ref(0)
const orderListArr = ref<Array<Array<any>>>([[], [], [], []])
const loadingArr = ref([false, false, false, false])
const finishedArr = ref([false, false, false, false])
const refreshingArr = ref([false, false, false, false])
const tabParams = ref([
  { page: 1, pageSize: 10, total: 0 },
  { page: 1, pageSize: 10, total: 0 },
  { page: 1, pageSize: 10, total: 0 },
  { page: 1, pageSize: 10, total: 0 },
])

// 删除订单功能
async function deleteOrder(orderId: string, sum: number) {
  try {
    // 显示确认对话框
    await showConfirmDialog({
      title: '确认删除',
      message: '确定要删除这个订单吗？删除后无法恢复。余额自动返回账户。',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      confirmButtonColor: '#ee0a24',
    })

    // 用户确认删除，调用删除接口
    const userinfo = storage.get('userInfo', 'local')
    if (!userinfo) {
      showNotify({ type: 'warning', duration: 500, message: '用户未登录' })
      return
    }

    const res = await request.post('/dragon/deleteOrderById', {
      id: orderId,
      order_buy_id: (userinfo as any).id,
      order_buy_user: (userinfo as any).username,
      order_buy_user_tel: (userinfo as any).tel_num,
      order_sum: sum,

    })

    if (res.code === 200 && res.msg === '订单删除成功') {
      // 从本地数据中移除该订单 - 优化：只处理当前标签页
      orderListArr.value[activeTab.value] = orderListArr.value[activeTab.value].filter(
        order => order.id !== orderId,
      )

      // 更新订单总数
      await getOrderCount(activeTab.value)
      showNotify({ type: 'success', duration: 500, message: '订单删除成功' })
    }
    else {
      Toast.fail(res.msg || '删除失败')
    }
  }
  catch (error) {
    if (error === 'cancel') {
      // 用户取消删除，不做任何操作
      return
    }
    console.error('删除订单失败:', error)
    Toast.fail('删除失败，请重试')
  }
}

// 获取订单总数
async function getOrderCount(tabIndex: number) {
  try {
    const userinfo = storage.get('userInfo', 'local')
    if (!userinfo || userinfo === null || userinfo === undefined) {
      showNotify({ type: 'warning', duration: 500, message: '用户未登录，无法获取订单列表' })
      return
    }
    // @ts-ignore
    const { username } = userinfo
    const res = await request.post('/dragon/orderCount', {
      order_type: tabIndex,
      order_buy_user: username,
    })
    tabParams.value[tabIndex].total = res.data || 0
  }
  catch (error) {
    console.error(`[TAB ${tabIndex}] 获取总数失败:`, error)
    tabParams.value[tabIndex].total = 0
  }
}

// 获取订单列表
async function getOrderList(tabIndex: number) {
  try {
    const userinfo = storage.get('userInfo', 'local')
    if (!userinfo) {
      showNotify({ type: 'warning', duration: 500, message: '用户未登录，无法获取订单列表' })
      return []
    }
    else {
      // @ts-ignore
      const { username } = storage.get('userInfo', 'local')
      const currentParams = tabParams.value[tabIndex]

      const res = await request.post('/dragon/orderList', {
        order_type: tabIndex,
        order_buy_user: username,
        pageSize: currentParams.pageSize,
        currentPage: currentParams.page,
      })

      // 关键修改：添加去重逻辑
      const newData = res.data || []
      const existingIds = new Set(orderListArr.value[tabIndex].map(item => item.id))
      const filteredData = newData.filter(item => !existingIds.has(item.id))

      return filteredData
    }
  }
  catch (error) {
    console.error(`[TAB ${tabIndex}] 获取列表失败:`, error)
    return []
  }
}

// 初始化TAB数据
async function initTabData(tabIndex: number) {
  // 重置状态
  tabParams.value[tabIndex] = {
    page: 1,
    pageSize: 10,
    total: 0,
  }
  loadingArr.value[tabIndex] = false
  finishedArr.value[tabIndex] = false
  refreshingArr.value[tabIndex] = false
  orderListArr.value[tabIndex] = []

  // 获取总数和第一页数据
  await getOrderCount(tabIndex)
  await getOrderList(tabIndex)
  await loadMoreData(tabIndex)
  onRefresh(tabIndex) // 确保初始数据加载完成后刷新列表
}

// 下拉刷新处理
async function onRefresh(tabIndex: number) {
  // 重置状态
  tabParams.value[tabIndex].page = 1
  finishedArr.value[tabIndex] = false
  orderListArr.value[tabIndex] = [] // 清空当前列表

  // 重新获取数据
  await getOrderCount(tabIndex)
  await loadMoreData(tabIndex)

  // 结束刷新
  refreshingArr.value[tabIndex] = false
}

// 加载更多数据 - 关键修改：修复重复加载问题
async function loadMoreData(tabIndex: number) {
  const tabParam = tabParams.value[tabIndex]

  // 检查是否已加载全部数据
  if (finishedArr.value[tabIndex])
    return

  // 计算最大页数
  const maxPage = Math.ceil(tabParam.total / tabParam.pageSize)
  if (tabParam.page > maxPage) {
    finishedArr.value[tabIndex] = true
    return
  }

  // 设置加载状态
  loadingArr.value[tabIndex] = true

  try {
    // 获取当前页数据
    const newData = await getOrderList(tabIndex)

    // 更新数据 - 只添加新数据
    orderListArr.value[tabIndex] = [
      ...orderListArr.value[tabIndex],
      ...newData,
    ]

    // 更新分页参数
    tabParam.page += 1

    // 检查是否加载完毕
    if (newData.length < tabParam.pageSize
      || orderListArr.value[tabIndex].length >= tabParam.total) {
      finishedArr.value[tabIndex] = true
    }
  }
  finally {
    loadingArr.value[tabIndex] = false
  }
}

// TAB切换处理
async function onTabChange(tabIndex: number) {
  // 关键修改：切换标签页时刷新数据
  onRefresh(tabIndex)
}

// 滚动到底部加载
async function onLoad(tabIndex: number) {
  await loadMoreData(tabIndex)
}

// 跳转详情页
function goDetail(id: number) {
  router.push(`/order/${id}`)
}

// 初始化第一个TAB的数据
onMounted(() => {
  initTabData(0)
})
</script>

<template>
  <div class="order-container">
    <!-- TAB标签区域 -->
    <div class="tabs-fixed">
      <van-tabs
        v-model:active="activeTab"
        class="order-tabs"
        line-width="40"
        color="#ff4d4f"
        sticky
        @change="onTabChange"
      >
        <van-tab
          v-for="(tab, idx) in tabs"
          :key="tab.key"
          :title="tab.title"
        >
          <!-- 订单列表区域（含下拉刷新） -->
          <van-pull-refresh
            v-model="refreshingArr[idx]"
            success-text="刷新成功"
            animation-duration="500"
            @refresh="() => onRefresh(idx)"
          >
            <div class="order-list-scroll">
              <van-list
                v-model:loading="loadingArr[idx]"
                :finished="finishedArr[idx]"
                finished-text="没有更多了"
                @load="() => onLoad(idx)"
              >
                <!-- 空状态提示 -->
                <div v-if="orderListArr[idx].length === 0 && !loadingArr[idx]" class="empty-tip">
                  暂无订单
                </div>

                <!-- 订单列表 -->
                <div v-else class="order-list">
                  <van-card
                    v-for="order in orderListArr[idx]"
                    :key="`${order.id}-${idx}`"
                    :title="order.order_name"
                    :desc="order.order_desc"
                    :thumb="order.order_img_url"
                    :price="order.order_sum"
                    class="order-card"
                    @click="goDetail(order.id)"
                  >
                    <!-- 图片中的标签 -->
                    <template #tags>
                      <van-tag v-if="order.order_type === 0" type="warning">
                        待处理
                      </van-tag>
                      <van-tag v-else-if="order.order_type === 1" type="primary">
                        处理中
                      </van-tag>
                      <van-tag v-else-if="order.order_type === 2" type="success">
                        已处理
                      </van-tag>
                    </template>
                    <template #footer>
                      <van-button
                        size="mini"
                        type="danger"
                        plain
                        @click.stop="deleteOrder(order.id, order.order_sum)"
                      >
                        删除
                      </van-button>
                    </template>
                  </van-card>
                </div>
              </van-list>
            </div>
          </van-pull-refresh>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<style scoped>
/* 样式保持不变 */
</style>
